const Koa = require('koa');
const Stream = require('stream');
const cors = require('@koa/cors');
const microBuild = require("./microBuild");
const {join} = require("path");
const {read} = require("fs");
const Router = require('koa-router');
const {tmpdir} = require("os");
const send = require('koa-send');
const app = new Koa();
const router = new Router();
const config = require("./config")

app.use(cors());

router.get('/download/:filename', async (ctx) => {
  const filename = ctx.params.filename;
  if (filename.includes('techdev')) {
    try {
      await send(ctx, filename, {root: tmpdir()});
    } catch (err) {
      if (err.status === 404) {
        ctx.throw(404, 'File not found');
      } else {
        ctx.throw(500, 'Internal Server Error');
      }
    }
  } else {
    ctx.throw(403, 'Err invalid file name.');
  }
});
router.get('/update', async (ctx, next) => {
  const readable = new Stream.Readable({
    read() {
    }
  });
  microBuild.updateCode(config.targetDir).then(res => {
    readable.push("Update child project success.\n");
    readable.push(null);
  }).catch(err => {
    readable.push("Update child project failed.\n");
    readable.push(err);
    readable.push(null);
  })
  ctx.type = 'text/event-stream';
  ctx.body = readable;
})
router.get('/build', async (ctx, next) => {
  const readable = new Stream.Readable({
    read() {
    }
  });
  microBuild.diffCode(config.baseDir)
    .then(files => {
      readable.push(new Date().toLocaleString() + " Code Diff success, updating git repository...\n")
      readable.push(`Diff files: \n${files.map(f => f.file).join("\n")}`)
      return microBuild.updateCode(config.baseDir, files)
    })
    .then(files => {
      readable.push(new Date().toLocaleString() + " Code update success, replacing files...\n")
      return microBuild.replaceCode(config.baseDir, config.targetDir, files);
    })
    .then(flag => {
      readable.push(new Date().toLocaleString() + " Code replace success, building...\n")
      readable.push(new Date().toLocaleString() + " Build operation will be slow, please wait...\n")
      return microBuild.build(config.targetDir);
    })
    .then(flag => {
      readable.push(new Date().toLocaleString() + " Build success, packaging...\n ")
      return microBuild.makeZip(join(config.targetDir, 'child'))
    })
    .then(fileName => {
      readable.push(new Date().toLocaleString() + " Package success, url is: \n")
      readable.push("\n" + config.host + "/download/" + fileName)
      readable.push(null);
    })
    .catch(err => {
      readable.push(new Date().toLocaleString() + " Error! Reason is: \n")
      readable.push(err)
      readable.push(null);
    })
  ctx.type = 'text/event-stream';
  ctx.body = readable;
})
app.use(router.routes());
app.listen(60000);
